﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Prism.Events;
using SoonCode.Core;
using SoonCode.FocusTest.Events;
using SoonCode.FocusTest.Models;
using SoonCode.FocusTest.ViewModels;

namespace SoonCode.FocusTest.Views.Teacher
{
    /// <summary>
    /// SelectTeacher.xaml 的交互逻辑
    /// </summary>
    public partial class SelectTeacher : UserControl
    {
        private SelectTeacherViewModel _viewModel;
        private IEventAggregator _aggregator;
        public SelectTeacher(IEventAggregator aggregator)
        {
            InitializeComponent();
            _aggregator = aggregator;
            _viewModel = (SelectTeacherViewModel)this.DataContext;
            initWebView();
        }
        private async void initWebView()
        {
            await WebView2.EnsureCoreWebView2Async();
            var profile = WebView2.CoreWebView2.Profile;
            await profile.ClearBrowsingDataAsync();
            WebView2.NavigationCompleted += WebView2_NavigationCompleted; ;
            WebView2.NavigationStarting += WebView2_NavigationStarting; ;
            WebView2.CoreWebView2.Settings.AreDevToolsEnabled = false;
            WebView2.CoreWebView2.ContextMenuRequested += (o, e) => e.Handled = true;
        }

        private void WebView2_NavigationStarting(object? sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationStartingEventArgs e)
        {
            LoadingCircle.Visibility = Visibility.Collapsed;
            if (e.Uri.Contains("http://select/"))
            {
                e.Cancel = true;
                
                string c = e.Uri.Substring(e.Uri.IndexOf("name=") + 5);
                c = WebUtility.UrlDecode(c);
                _viewModel.SetSelectTeacher(c);
            }
        }

        private void WebView2_NavigationCompleted(object? sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationCompletedEventArgs e)
        {
            LoadingCircle.Visibility = Visibility.Hidden;
        }
    }
}
